package com.bingo.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bingo.demo.pojo.Album;
import com.bingo.demo.pojo.Comment;
import com.bingo.demo.pojo.Essay;
import com.bingo.demo.pojo.User;
import com.bingo.demo.service.AlbumService;
import com.bingo.demo.service.CommentService;
import com.bingo.demo.service.EssayService;
import com.bingo.demo.utils.uploadUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class EssayController {

    @Autowired
    EssayService essayService;
    @Autowired
    CommentService commentService;
    @Autowired
    AlbumService albumService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("uploadImg.action")
    @ResponseBody
    public JSONObject uploadImg(HttpServletRequest request) throws IOException {
        MultipartFile imgFile;
        MultipartRequest multipartRequest=(MultipartRequest) request;
        imgFile = multipartRequest.getFile("file");
        System.out.println("收到上传请求");
        if(imgFile.isEmpty()){
            System.out.println("上传图片失败");
        }
        JSONObject json = new JSONObject();
        //String s = uploadUtil.uploadPicture(imgFile);
        String s = uploadUtil.qiniuUpload(imgFile);
        System.out.println(s);
        json.put("code",0);
        json.put("msg","图片添加成功");
        json.put("imgUrl",s);
        return json;
    }

    @RequestMapping("publish.action")
    @ResponseBody
    public JSONObject addEssay(HttpServletRequest request,HttpSession session){
        JSONObject json = new JSONObject();
        String title = request.getParameter("title");
        String tag = request.getParameter("tag");
        String content = request.getParameter("content");
        String code = request.getParameter("code");
        String userName = request.getParameter("userName");
        String imgUrl = request.getParameter("imgUrl");
        Integer authority=0;
        //获取登录者的id
        User loginUser = (User) session.getAttribute("loginUser");
        Integer userId = loginUser.getId();
        if(request.getParameter("authority")!=null&&!request.getParameter("authority").equals("")){
            authority=Integer.parseInt(request.getParameter("authority"));
        }
        Essay essay = new Essay();
        if(title!=null&&tag!=null&&content!=null&&authority!=null&&imgUrl!=null){
            essay.setTitle(title);
            essay.setContent(content);
            essay.setCode(code);
            essay.setUserName(userName);
            essay.setTag(tag);
            essay.setAuthority(authority);
            essay.setUserId(userId);
            if(!request.getParameter("albumId").equals("empty")){
                Integer albumId = Integer.parseInt(request.getParameter("albumId"));
                Album album = albumService.findById(albumId);
                essay.setImgUrl(album.getImgUrl());
            }else if(!imgUrl.equals("")){
                essay.setImgUrl(imgUrl);
            }else essay.setImgUrl("img/empty.jpg");
            essayService.addEssay(essay);
        }
        json.put("code",0);
        json.put("msg","发表成功");
        return json;

    }

    @RequestMapping("essayDelete.action")
    @ResponseBody
    public JSONObject deleteEssay(HttpServletRequest request){
        String essayId = request.getParameter("essayId");
        System.out.println(essayId+"essayId");
        Integer id = Integer.parseInt(essayId);
        Essay essay = essayService.findById(id);
        System.out.println(essay.getImgUrl());
        //删除数据库记录,还必须删除文件
        uploadUtil.deletePicture(essay.getImgUrl());
        essayService.deleteEssayById(id);
        JSONObject json = new JSONObject();
        json.put("code",0);
        json.put("msg","删除成功,刷新页面后生效");
        return json;
    }

    @RequestMapping("toMyBlog.action")
    public String toMyBlog(HttpSession session, Model model){
        if(session.getAttribute("loginUser") == null){
            model.addAttribute("msg","您还没有登录,请先登录");
            return "login";
        }
        User user = (User) session.getAttribute("loginUser");
        List<Essay> myEssayList = essayService.findEssayByUserId(user.getId());
        //找到评论列表
        List<Comment> allList = new ArrayList<>();
        for(Essay essay:myEssayList){
            List<Comment> list = commentService.findByEssayId(essay.getId());
            allList.addAll(list);
        }
        session.setAttribute("commentList",allList);
        if(myEssayList.isEmpty()){
            session.setAttribute("emptyImg","img/empty.jpg");
        }
        //只返回5条数据
        if(myEssayList.size() > 5){
            List<Essay> list = myEssayList.subList(0, 5);
            session.setAttribute("myEssayList",list);
            session.setAttribute("hasNextMyBlog",1);
        }else {
            session.setAttribute("myEssayList",myEssayList);
            session.setAttribute("hasNextMyBlog",0);
        }
        session.setAttribute("hasLast",0);
        session.setAttribute("pageNumMyBlog",1);
        return "myBlog";
    }

    @RequestMapping("toNextMyBlogPage.action")
    public String toNextMyBlogPage(HttpSession session){
        if(session.getAttribute("hasNextMyBlog").equals(0))return "myBlog";
        Integer page = null;
        try {
            User user = (User) session.getAttribute("loginUser");
            if(session.getAttribute("pageNumMyBlog")!=null){
                page = (Integer) session.getAttribute("pageNumMyBlog")+1;
            }
            List<Essay> myEssayList = essayService.findEssayByUserId(user.getId());
            if(myEssayList.size() > page*5){
                List<Essay> list = myEssayList.subList((page-1)*5, page*5-1);
                session.setAttribute("myEssayList",list);
                session.setAttribute("hasNextMyBlog",1);
            }else{
                List<Essay> list = myEssayList.subList((page-1)*5,myEssayList.size());
                session.setAttribute("myEssayList",list);
                session.setAttribute("hasNextMyBlog",0);
            }
            session.setAttribute("pageNumMyBlog",page);
            //如果这个跳转下一页的方法被调用,则说明必有上一页
            session.setAttribute("hasLastMyBlog",1);
        }catch (IllegalArgumentException e){
            page = page-1;
            session.setAttribute("pageNumMyBlog",page);
            return "myBlog";
        }
        return "myBlog";
    }

    @RequestMapping("toLastMyBlogPage.action")
    public String toLastMyBlogPage(HttpSession session){
        User user = (User) session.getAttribute("loginUser");
        Integer page = (Integer) session.getAttribute("pageNumMyBlog")-1;
        try {
            //此方法被调用,则必有下一页
            session.setAttribute("hasNextMyBlog",1);
            //参数为1,表示权限为公开的文章
            List<Essay> myEssayList = essayService.findEssayByUserId(user.getId());
            List<Essay> list = myEssayList.subList((page - 1) * 5, page * 5 - 1);
            session.setAttribute("myEssayList",list);
            //如果当前页为首页,则无上一页
            if(page == 1)session.setAttribute("hasLastMyBlog",0);
            //返回之前设置新的页码
            session.setAttribute("pageNumMyBlog",page);
        }catch (IllegalArgumentException e){
            page = page+1;
            session.setAttribute("pageNumMyBlog",page);
        }finally {
            return "myBlog";
        }
    }

    @RequestMapping("searchEssayByTitle.action")
    public String searchEssayByTitle(HttpServletRequest request,HttpSession session){
        String searchKey = request.getParameter("searchKey");
        //关键字按标题搜索
        List<Comment> allList = new ArrayList<>();
        List<Essay> essayList = essayService.findEssayByTitle(searchKey);
        for(Essay essay:essayList){
            List<Comment> list = commentService.findByEssayId(essay.getId());
            allList.addAll(list);
        }
        session.setAttribute("essayBySearch",essayList);
        session.setAttribute("commentList",allList);
        return "essayBySearch";
    }

    @RequestMapping("searchEssayByNumber.action")
    public String searchEssayByNumber(HttpServletRequest request,HttpSession session){
        String essayNumber = request.getParameter("essayNumber");
        //将essayNumber作为关键字进行查找
        Essay essay = essayService.findEssayByNumber(essayNumber);
        if(essay!=null){
            List<Comment> list = commentService.findByEssayId(essay.getId());
            if(list!=null){
                session.setAttribute("commentList",list);
            }
            session.setAttribute("essayBySearchNumber",essay);
        }
        //return "essayBySearch";
        return "details";
    }


}
